package top.changelife.learn.springmvc.socket.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author cz
 * @date 2019/12/22 11:48
 */
public class AioServer {
    public static void main(String[] args) {
        try {
            AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8080));
            while (true) {
                Future<AsynchronousSocketChannel> future = serverChannel.accept();
                // 获取连接完成后返回的 channel，这一步是阻塞的
                AsynchronousSocketChannel client = future.get();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                Future<Integer> readCount = client.read(buffer);
                System.out.println(readCount.get());
                buffer.flip();
                String receivedString = Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
                System.out.println(receivedString);
                Future<Integer> writeCount = client.write(ByteBuffer.wrap("hello".getBytes("UTF-8")));
                writeCount.get();
                client.close();
                if (receivedString.startsWith("end")) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
